package com.gec.hrm.filter;

import com.gec.hrm.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter({"*.action","*.html"})
public class LoginFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse res=(HttpServletResponse) servletResponse;

        String path=req.getServletPath();

        if("/login.action".equals(path)||"/register.action".equals(path)
            ||"/jsp/login.html".equals(path)){
            filterChain.doFilter(req,res);
        }else{
            HttpSession session=req.getSession();
            User user= (User) session.getAttribute("user");
            // 登录成功登录状态会一直记录在session中，知道退出
            // 即没退出直接访问首页是不会拦截的
            if(user!=null){
                filterChain.doFilter(req,res);
            }else{
                res.sendRedirect("/jsp/login.html");
            }
        }
    }

    public void destroy() {
//        Filter.super.destroy();
    }
}
